package com.faxsun.web.endpoint;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import mblog.core.pojos.Post;
import mtons.modules.pojos.Page;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.persist.entity.FollowListPO;
import com.faxsun.core.persist.entity.UserPO;
import com.faxsun.core.pojos.enums.FollowListType;
import com.faxsun.core.pojos.enums.PostType;
import com.faxsun.core.service.FollowListService;
import com.faxsun.core.service.PostService;
import com.faxsun.core.service.UserService;
import com.faxsun.web.utils.StaticResourceUrlProcessor;

/**
 * 提供与资讯文章相关的restful接口
 * 
 * @author songdragon 2015年5月15日
 *
 */
@Controller
@RequestMapping("/api/v1")
public class InfoNotificationEndpoint {

	private static final Logger LOG = LoggerFactory
			.getLogger(InfoNotificationEndpoint.class);

	@Autowired
	protected PostService postService;

	@Autowired
	protected UserService userService;

	@Autowired
	protected FollowListService followListService;

	/**
	 * 获取最近max篇资讯文章
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/newinfo", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<InfoJson> pullNewTenInfos(HttpServletRequest request,
			@RequestParam(value = "max", defaultValue = "5") Integer max) {
		List<InfoJson> ret = new ArrayList<InfoJson>();
		Page page = new Page(max);
		postService.paging(page, PostType.INFO);
		try {
			@SuppressWarnings("unchecked")
			List<Post> posts = (List<Post>) page.getResults();
			ret.addAll(this.transformToInfoJson(request, posts));
		} catch (Exception e) {
			LOG.error("Exception when fetch the newest " + max + " infomation",
					e);
		}
		return ret;
	}

	@RequestMapping(value = "/myinfo", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<InfoJson> pullRecentFavoriteInfo(HttpServletRequest request,
			@RequestParam(value = "max", defaultValue = "5") Integer max,
			@RequestParam(value = "customerId") Long uid) {

		List<InfoJson> ret = new ArrayList<InfoJson>();
		try {
			UserPO user = userService.findUserByCustomerId(uid);
			List<Post> posts = retrieveUserFavoritePosts(max, user.getId(),
					FollowListType.INFOMATION);
			ret.addAll(this.transformToInfoJson(request, posts));

		} catch (Exception e) {
			LOG.error("Exception when fetch the newest "
					+ FollowListType.INFOMATION + max + " infomation", e);
		}
		return ret;
	}

	@RequestMapping(value = "/myevaluation", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
	@ResponseBody
	public List<InfoJson> pullRecentFavoriteEvaluation(
			HttpServletRequest request,
			@RequestParam(value = "max", defaultValue = "5") Integer max,
			@RequestParam(value = "customerId") Long uid) {

		List<InfoJson> ret = new ArrayList<InfoJson>();
		try {
			UserPO user = userService.findUserByCustomerId(uid);
			List<Post> posts = retrieveUserFavoritePosts(max, user.getId(),
					FollowListType.EVALUATION);
			ret.addAll(this.transformToInfoJson(request, posts));

		} catch (Exception e) {
			LOG.error("Exception when fetch the newest "
					+ FollowListType.EVALUATION + max + " infomation", e);
		}
		return ret;
	}

	private List<Post> retrieveUserFavoritePosts(int max, long uid,
			FollowListType type) throws Exception {

		Page page = new Page(max);
		this.followListService.findAllMyFollows(page, uid, type.getIntValue());

		@SuppressWarnings("unchecked")
		List<FollowListPO> followList = (List<FollowListPO>) page.getResults();

		List<Post> posts = new ArrayList<Post>();
		for (FollowListPO po : followList) {
			Post p = postService.get(po.getUid());
			if (p != null) {
				posts.add(p);
			}
		}

		return posts;
	}

	private List<InfoJson> transformToInfoJson(HttpServletRequest request,
			List<Post> posts) {
		List<InfoJson> ret = new ArrayList<InfoJson>();
		String host = "http://" + request.getServerName();
		String context = request.getContextPath();
		for (Post post : posts) {

			ret.add(InfoJson.constructFromPost(post, host, context));
		}
		return ret;
	}
}

/**
 * 资讯JSON实体类
 * 
 * @author songdragon 2015年5月15日
 *
 */
class InfoJson implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3772667682513437016L;
	/**
	 * 资讯名称
	 */
	public String title;
	/**
	 * 摘要？
	 */
	public String description;
	/**
	 * 文章地址,Format:http://host/context/url
	 */
	public String url;
	/**
	 * 封面图片地址,Format: http://host/context/url
	 */
	public String picUrl;

	/**
	 * 根据Post填充JSON实体
	 * 
	 * @param post
	 * @param host
	 *            服务器主机名，用于构造文章和图片url
	 * @param context
	 *            服务器context path，用于构造文章和图片url
	 * @return
	 */
	public static InfoJson constructFromPost(Post post, String host,
			String context) {
		InfoJson json = new InfoJson();
		json.description = post.getSummary();
		// 由于editor原因，服务器存储的是/contextpath/url
		StringBuffer sb = new StringBuffer(post.getSnapshot().getOriginal());
		if (!sb.toString().startsWith("http://")) {
			sb.insert(0, host);
		}
		json.picUrl = StaticResourceUrlProcessor.replaceUrlWithCDNUrl(sb
				.toString());
		if (!StringUtils.isEmpty(json.picUrl) && json.picUrl.startsWith("//")) {
			json.picUrl = "http:" + json.picUrl;
		}
		json.title = post.getTitle();
		// 服务器不存储文章url，此处需拼接
		// TODO:/post/view常量放入单独配置类中
		json.url = host + context + "/post/view/" + post.getId();
		return json;
	}
}